import { HttpException, Injectable } from '@nestjs/common';
import { CreateArticleDto } from './dto/create-article.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { UpdateArticleDto } from './dto/update-article.dto';

@Injectable()
export class ArticleService {
  constructor(private readonly prismaService: PrismaService) {}
  async create(createArticleDto: CreateArticleDto, authorId: number) {
    console.log(authorId);
    try {
      const res = await this.prismaService.article.create({
        data: {
          ...createArticleDto,
          authorId,
        },
      });
      console.log(res);
      return {
        code: 200,
        message: '创建成功',
      };
    } catch (error) {
      console.log(error);
      throw new HttpException('创建失败', 400);
    }
  }

  async findAll(id: number) {
    try {
      const res = await this.prismaService.article.findMany({
        where: { authorId: id },
        include: {
          author: {
            select: {
              username: true,
            },
          },
        },
      });
      return res;
    } catch (error) {
      throw new HttpException('查询失败', 400);
    }
  }

  async findOne(id: number) {
    try {
      const res = await this.prismaService.article.findUnique({
        where: { id },
      });
      return res;
    } catch (error) {
      throw new HttpException('查询失败', 400);
    }
  }

  async remove(id: number) {
    return this.prismaService.article.delete({
      where: { id },
    });
  }

  async update(id: number, updateArticleDto: UpdateArticleDto) {
    return this.prismaService.article.update({
      where: { id },
      data: updateArticleDto,
    });
  }
}
